package com.stxx.filesyn.controller;


import org.noear.snack.core.utils.StringUtil;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Fuzhenlei
 * @date 2025/01/13 15:15
 */
@Controller
@Mapping("/files")
public class FilesController {
    @Inject("${file-path}")
    private String filePath;
    private static String path;



    @Get
    @Mapping("/path")
    private String getPath(){
        if(path!=null){
            return path;
        }
        if(!StringUtil.isEmpty(filePath)){
            path = filePath;
        }else {
            String userHome = System.getProperty("user.home");
            String desktopPath;
            // 根据操作系统确定桌面路径
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                path = Paths.get(userHome, "Desktop","会议文件").toString();
            } else { // 假设是Unix-like系统，包括Linux和macOS
                path = Paths.get(userHome, "Desktop","会议文件").toString();
            }
        }
        return path;
    }

    @Get
    @Mapping("/list")
    public List<String> list() {
        File file = new File(getPath());
        if(!file.exists()){
            file.mkdirs();
        }
        List<String> list = new ArrayList<>();
        File[] files = file.listFiles();
        if (files != null) {
            for (File subFile : files) {
                if(subFile.isDirectory()){
                    continue;
                }
                list.add(subFile.getName());
            }
        }
        return list;
    }

    @Get
    @Mapping("/download")
    public void download(@Path String fn, Context ctx){
        File file = new File(Paths.get(getPath(), fn).toString());
        if(!file.exists()){
            ctx.output("file not found");
            return;
        }

        try(InputStream inputStream = new FileInputStream(file)) {
            ctx.contentType("application/octet-stream");
            ctx.contentLength(file.length());
            ctx.headerAdd("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fn) + "\"");
            ctx.output(inputStream);
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
